package com.acxy.b2b2c.controller;

import com.acxy.ants.core.annotation.Autowired;
import com.acxy.ants.resful.annotation.Controller;
import com.acxy.ants.resful.annotation.GET;
import com.acxy.ants.resful.annotation.POST;
import com.acxy.ants.resful.annotation.Param;
import com.acxy.ants.resful.bean.Page;
import com.acxy.ants.resful.render.Json;
import com.acxy.b2b2c.entity.Goods;
import com.acxy.b2b2c.service.GoodsService;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-10-09
 */
@Controller("goods")
public class GoodsAjax {

    @Autowired
    private GoodsService goodsService;

    /**
     * 获取商品分页列表
     * @param pageIndex 当前页
     * @param pageSize 每页大小
     * @param catIds 所属分类
     * @return
     */
    @POST("/page")
    public Object page(@Param(value = "^(-|\\+)?\\d+$", msg = "only positive numbers can be entered!") Integer pageIndex
            , @Param(value = "^(-|\\+)?\\d+$", msg = "only positive numbers can be entered!") Integer pageSize
            , Long[] catIds) throws SQLException {
        Page page = goodsService.queryPage(pageIndex, pageSize, catIds);
        return Json.ui(page);
    }

    /**
     * 添加商品数据
     *
     * @param goods 商品数据
     * @return
     */
    @POST("/save")
    public Object save(Goods goods) {
        goodsService.save(goods);
        return Json.success("ok");
    }

    /**
     * 根基商品ID查询商品
     * @param id 商品ID
     * @return
     */
    @GET("/find")
    public Object find(@Param Long id) {
        Goods goods = goodsService.find(id);
        return Json.success(goods);
    }

    /**
     * 根基商品对象修改商品
     * @param goods 商品对象
     * @return
     */
    @POST("/update")
    public Object update(Goods goods) {
        int res = goodsService.update(goods);
        return Json.success(res);
    }

    /**
     * 删除商品以及图片
     * @param ids 商品集合ID
     * @param request
     * @return
     */
    @POST("/delete")
    public Object delete(Long[] ids, HttpServletRequest request) {
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        //存在旧文件就删除
        int result = goodsService.delete(ids, rootPath);
        return Json.success(result);
    }

    /**
     * 修改商品状态控制前端隐藏与显示
     *
     * @param id   商品ID
     * @param show 0/隐藏 1/显示
     * @return
     */
    @POST("/checkShow")
    public Object checkShow(Long id, int show) {
        int res = goodsService.checkShow(id, show);
        return Json.success(res);
    }

    /**
     * 修改商品排序
     * @param id   商品ID
     * @param sort 排序
     * @return
     */
    @POST("/updateSort")
    public Object updateSort(@Param Long id, Integer sort) {
        int res = goodsService.updateSort(id, sort);
        return Json.success(res);
    }
}
